package org.lab.tracecash.services;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;

import org.lab.tracecash.jpa.NamedQueries;
import org.lab.tracecash.model.Account;
import org.lab.tracecash.model.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AccountService {

	private static final Logger LOG = LoggerFactory.getLogger(AccountService.class);

	@Inject
	private Provider<EntityManager> entityManagerProvider;

	public List<Account> getAll() {
		return entityManagerProvider.get().createQuery("select a from Portfolio a order by a.id", Account.class).getResultList();
	}

	public Account findById(Long id) {
		return entityManagerProvider.get().find(Account.class, id);
	}

	public Account getByName(String name, Long ownerId) {
		TypedQuery<Account> query = entityManagerProvider.get().createNamedQuery(NamedQueries.ACCOUNT_GET_BY_NAME_AND_OWNER, Account.class);
		try {
			return query.setParameter("name", name).setParameter("ownerId", ownerId).getSingleResult();
		} catch (NoResultException ex) {
			LOG.info(String.format("Missing portfolio: %s (ownerId: %s)", name, ownerId));
			return null;
		}
	}

	public List<Transaction> getTransactions(Long id) {
		EntityManager entityManager = entityManagerProvider.get();
		TypedQuery<Transaction> query = entityManager.createNamedQuery(NamedQueries.TRANSACTION_GET_BY_ACCOUNT, Transaction.class);
		return query.setParameter("id", id).getResultList();
	}
}
